#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_gpio.h"
#include "button.h"


int mode = 1;  // 全局模式变量

// 获取按键状态函数
unsigned char getButtonState(WifiIotGpioIdx id, WifiIotGpioValue *val)
{
    // 将GPIO索引转换为对应的IO名称
    WifiIotIoName ioName = (WifiIotIoName)(WIFI_IOT_IO_NAME_GPIO_0 + id);
    GpioGetInputVal(ioName, val);
    return *val;
}

int buttonMode(void) {
    return mode;
}

void buttonInit(void)
{
    GpioInit();
    // 初始化LED灯 (GPIO2)
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_IO_FUNC_GPIO_2_GPIO);
    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_GPIO_DIR_OUT);
    
    // 初始化F1按键 (GPIO11)
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_IO_FUNC_GPIO_11_GPIO);
    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_GPIO_DIR_IN);
    IoSetPull(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_IO_PULL_UP);
    
    // 初始化F2按键 (GPIO12)
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_IO_FUNC_GPIO_12_GPIO);
    GpioSetDir(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_GPIO_DIR_IN);
    IoSetPull(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_IO_PULL_UP);
}

void buttonTestTask(void* arg)
{
    (void) arg; 
    buttonInit();
    unsigned char lastF1State = 1; // 初始状态为未按下
    unsigned char lastF2State = 1;
    
    while(1)
    {
        WifiIotGpioValue val;
        unsigned char F1_State = getButtonState(F1, &val);
        unsigned char F2_State = getButtonState(F2, &val);

        // F1按键检测与去抖
        if (F1_State != lastF1State) {
            osDelay(50); // 去抖动延时
            F1_State = getButtonState(F1, &val);
            if (F1_State != lastF1State) {
                lastF1State = F1_State;
                if (F1_State == 0) { // 按下状态
                    mode = 1;
                    GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_2, 1); // LED亮
                }
            }
        }

        // F2按键检测与去抖
        if (F2_State != lastF2State) {
            osDelay(50); // 去抖动延时
            F2_State = getButtonState(F2, &val);
            if (F2_State != lastF2State) {
                lastF2State = F2_State;
                if (F2_State == 0) { // 按下状态
                    mode = 0;
                    GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_2, 0); // LED灭
                }
            }
        }
        
        osDelay(100); // 主循环延时
    }
}

void setButtonMode(int m) {
    mode = m;
}

void buttonThread(void) {
    osThreadAttr_t attr = {
        .name = "ButtonTask",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U,
        .stack_mem = NULL,
        .stack_size = 1024,
        .priority = osPriorityNormal,
    };
    
    if (osThreadNew(buttonTestTask, NULL, &attr) == NULL) {  
        printf("Failed to create ButtonTestTask!\n");
    }
}

APP_FEATURE_INIT(buttonThread);